package com.dream.testtubebaby.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dream.testtubebaby.R;
import com.dream.testtubebaby.adapter.DocRequireAdapter;
import com.dream.testtubebaby.adapter.MyToldListAdapter;
import com.dream.testtubebaby.data.AddToldData;
import com.dream.testtubebaby.data.ToldItemDao;
import com.dream.testtubebaby.net.ServerStub;
import com.dream.testtubebaby.okhttp.OkHttpClientManager;
import com.dream.testtubebaby.utils.AppUtil;
import com.dream.testtubebaby.utils.ImageLoader;
import com.dream.testtubebaby.utils.LanguageUtils;
import com.dream.testtubebaby.utils.NetUtil;
import com.dream.testtubebaby.utils.SharePreferencesManager;
import com.dream.testtubebaby.utils.StatusBarCompat;
import com.dream.testtubebaby.utils.ToastUtil;
import com.squareup.okhttp.Request;

public class MyPeriodActivity extends AppCompatActivity implements
		OnClickListener, OnItemLongClickListener, OnItemClickListener,
		MyToldListAdapter.ToldDetailListener {
	public static final String UPDATE_PERIOD_REVEIVER_ACTION = "update_period_receiver_action";
	public static final int TOLD_COMMIT_REQUEST_CODE = 0x321;
	private TextView wait_for_doctor_advice_tv;
	private ListView doc_require_list;
	private DocRequireAdapter mDocRequireAdapter;
	private List<AddToldData> docRequireData;
	private List<AddToldData> docActionData;
	private ListView my_told_listview;
	private MyToldListAdapter mMyToldListAdapter;

	private UpdatePeriodReveiver mUpdatePeriodReveiver;
	private SharePreferencesManager mSharePreferencesManager;
	private ProgressDialog mProgressDialog;
	private ToldItemDao mToldItemDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_period);
		StatusBarCompat.compat(this,
				getResources().getColor(R.color.status_bar_color));
		mSharePreferencesManager = new SharePreferencesManager(this);
		initView();
		initListView();
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage(getResources().getString(
				R.string.told_complete_commit_updateing));
		mUpdatePeriodReveiver = new UpdatePeriodReveiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(UPDATE_PERIOD_REVEIVER_ACTION);
		registerReceiver(mUpdatePeriodReveiver, filter);
		mToldItemDao = new ToldItemDao(this);
		if (NetUtil.checkNet(this)) {
			updateAddToldlist();
			updateAddToldActionlist();
		} else {
			mProgressDialog.show();
			List<AddToldData> mAddToldDatas = mToldItemDao.list();
			docRequireData.clear();
			docRequireData.addAll(mAddToldDatas);
			mDocRequireAdapter.notifyDataSetChanged();
			mMyToldListAdapter.notifyDataSetChanged();
			mProgressDialog.dismiss();
		}
	}

	private void initListView() {
		doc_require_list = (ListView) findViewById(R.id.doc_require_list);
		docRequireData = new ArrayList<AddToldData>();
		mDocRequireAdapter = new DocRequireAdapter(this, docRequireData,
				R.layout.doc_require_item);
		doc_require_list.setAdapter(mDocRequireAdapter);
		doc_require_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				showRequireItemDialog(position);
			}
		});

		my_told_listview = (ListView) findViewById(R.id.my_told_listview);
		docActionData = new ArrayList<AddToldData>();
		mMyToldListAdapter = new MyToldListAdapter(this, docActionData,
				R.layout.add_told_common_view);
		mMyToldListAdapter.setToldDetailListener(this);
		my_told_listview.setAdapter(mMyToldListAdapter);
		my_told_listview.setOnItemClickListener(this);
		// my_told_listview.setOnItemLongClickListener(this);
	}

	private void initView() {
		ImageView back_icon_view = (ImageView) findViewById(R.id.my_period_back_icon);
		back_icon_view.setOnClickListener(this);
		wait_for_doctor_advice_tv = (TextView) findViewById(R.id.wait_for_doctor_advice_tv);
		wait_for_doctor_advice_tv.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && resultCode == Activity.RESULT_OK) {
			if (requestCode == TOLD_COMMIT_REQUEST_CODE) {
				updateAddToldActionlist();
			}
		}
	}

	private void updateAddToldActionlist() {
		mProgressDialog.show();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uid", String.valueOf(mSharePreferencesManager.readUserId()));
		OkHttpClientManager.postAsyn(ServerStub.BASEURL
				+ "m=Home&c=App&a=getMyDoctorAdviceAction",
				new OkHttpClientManager.ResultCallback<String>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(MyPeriodActivity.this,
								R.string.server_error);
						mProgressDialog.dismiss();
					}

					@Override
					public void onResponse(String response) {
						try {
							// {"id":"17","doctorid":"100000001","fromtime":"2015-9-24","totime":"2015-9-27","stepname":"\u9a8c\u8840",
							// "f_steptodo":"1","drug":"\u8fbe\u83f2\u6797","howmuch":"0.05mg","f_finished":"1","finishtime":"1442983337"}
							docActionData.clear();
							JSONObject obj = new JSONObject(response);
							if (obj != null) {
								int result = obj.getInt("result");
								if (result == 0) {
									JSONArray jsonMessage = new JSONArray(obj
											.getString("actions"));
									int length = jsonMessage.length();
									for (int i = 0; i < length; i++) {
										JSONObject jsonObject = (JSONObject) jsonMessage
												.get(i);
										AddToldData addToldData = AddToldData
												.getAddToldListNode(jsonObject);
										addToldData.setStepname(LanguageUtils
												.getToldProjectWithCode(
														MyPeriodActivity.this,
														addToldData
																.getStepname()));
										addToldData.setDrug(LanguageUtils
												.getInjectionMedicineStringWithCode(
														MyPeriodActivity.this,
														addToldData.getDrug()));
										addToldData.setHowmuch(LanguageUtils
												.getQuantitieStringWithCode(
														MyPeriodActivity.this,
														addToldData
																.getHowmuch()));
										docActionData.add(addToldData);
									}
									if (length > 0) {
										wait_for_doctor_advice_tv
												.setVisibility(View.INVISIBLE);
									}
									Collections.reverse(docActionData);
									// mToldItemDao.deleteAll();
									// mToldItemDao.add(docActionData);
								}
							}
							mProgressDialog.dismiss();
							mMyToldListAdapter.notifyDataSetChanged();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, params);
	}

	private void updateAddToldlist() {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uid", String.valueOf(mSharePreferencesManager.readUserId()));
		OkHttpClientManager.postAsyn(ServerStub.BASEURL
				+ "m=Home&c=App&a=getMyDoctorAdvice",
				new OkHttpClientManager.ResultCallback<String>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(MyPeriodActivity.this,
								R.string.server_error);
					}

					@Override
					public void onResponse(String response) {
						try {
							// {"id":"17","doctorid":"100000001","fromtime":"2015-9-24","totime":"2015-9-27","stepname":"\u9a8c\u8840",
							// "f_steptodo":"1","drug":"\u8fbe\u83f2\u6797","howmuch":"0.05mg","f_finished":"1","finishtime":"1442983337"}
							docRequireData.clear();
							JSONObject obj = new JSONObject(response);
							if (obj != null) {
								int result = obj.getInt("result");
								if (result == 0) {
									JSONArray jsonMessage = new JSONArray(obj
											.getString("advices"));
									int length = jsonMessage.length();
									for (int i = 0; i < length; i++) {
										JSONObject jsonObject = (JSONObject) jsonMessage
												.get(i);
										AddToldData addToldData = AddToldData
												.getAddToldListNode(jsonObject);
										addToldData.setStepname(LanguageUtils
												.getToldProjectWithCode(
														MyPeriodActivity.this,
														addToldData
																.getStepname()));
										addToldData.setDrug(LanguageUtils
												.getInjectionMedicineStringWithCode(
														MyPeriodActivity.this,
														addToldData.getDrug()));
										addToldData.setHowmuch(LanguageUtils
												.getQuantitieStringWithCode(
														MyPeriodActivity.this,
														addToldData
																.getHowmuch()));
										docRequireData.add(addToldData);
									}
									if (length > 0) {
										wait_for_doctor_advice_tv
												.setVisibility(View.INVISIBLE);
									}
									Collections.reverse(docRequireData);
									mToldItemDao.deleteAll();
									mToldItemDao.add(docRequireData);
								}
							}
							mDocRequireAdapter.notifyDataSetChanged();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, params);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.my_period_back_icon:
			super.onBackPressed();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mUpdatePeriodReveiver);
	}

	private class UpdatePeriodReveiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(UPDATE_PERIOD_REVEIVER_ACTION)) {

			}
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			final int position, long id) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage(R.string.remove_told_dialog_msg);
		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						long id = docRequireData.get(position).getId();
						removeTold(id);
					}
				});
		builder.create().show();
		return false;
	}

	private void removeTold(long id) {
		mProgressDialog.show();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("id", String.valueOf(id));
		params.put("op", "del");
		OkHttpClientManager.postAsyn(ServerStub.BASEURL
				+ "m=Home&c=App&a=OperateDoctorAdvice",
				new OkHttpClientManager.ResultCallback<Integer>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(MyPeriodActivity.this,
								R.string.server_error);
						mProgressDialog.dismiss();
					}

					@Override
					public void onResponse(Integer code) {
						if (code == 200) {
							updateAddToldlist();
							updateAddToldActionlist();
						}
						mProgressDialog.dismiss();
					}
				}, params);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, final View view,
			final int position, long id) {
		final AddToldData addToldData = docActionData.get(position);
		String stepname = addToldData.getStepname();
		if (stepname.equals(getResources().getStringArray(
				R.array.told_project_array)[2])
				|| stepname.equals(getResources().getStringArray(
						R.array.told_project_array)[3])) {
			showModifyAndLookDialog(view, position, addToldData);
		} else if (addToldData.getFinishtime() == 0) {
			AlertDialog.Builder builder = new Builder(MyPeriodActivity.this);
			builder.setMessage(R.string.remove_told_dialog_msg);
			builder.setNegativeButton(android.R.string.cancel,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					});
			builder.setNeutralButton(R.string.told_modify_title,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							AddToldData item = docActionData.get(position);
							startModifyToldActivity(item);
						}
					});
			builder.create().show();
		}
	}

	private void showModifyAndLookDialog(final View view, final int position,
			final AddToldData addToldData) {
		AlertDialog.Builder builder = new Builder(MyPeriodActivity.this);
		builder.setMessage(R.string.remove_told_dialog_msg);
		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.setPositiveButton(R.string.told_look_title,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// long id = docActionData.get(position).getId();
						// removeTold(id);
						String stepname = addToldData.getStepname();
						if (stepname.equals(getResources().getStringArray(
								R.array.told_project_array)[2])) {// bchao
							showBchaoPopWindow(view, addToldData);
						} else if (stepname.equals(getResources()
								.getStringArray(R.array.told_project_array)[3])) {// yanxue
							showYanxuePopWindow(view, addToldData);
						}
					}
				});
		builder.setNeutralButton(R.string.told_modify_title,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						AddToldData item = docActionData.get(position);
						onToldDetailonClick(item);
					}
				});
		builder.create().show();
	}

	private int leftruanViewIds[] = { R.id.l_ruan_val_1, R.id.l_ruan_val_2,
			R.id.l_ruan_val_3, R.id.l_ruan_val_4, R.id.l_ruan_val_5,
			R.id.l_ruan_val_6, R.id.l_ruan_val_7, R.id.l_ruan_val_8 };
	private int rightruanViewIds[] = { R.id.r_ruan_val_1, R.id.r_ruan_val_2,
			R.id.r_ruan_val_3, R.id.r_ruan_val_4, R.id.r_ruan_val_5,
			R.id.r_ruan_val_6, R.id.r_ruan_val_7, R.id.r_ruan_val_8 };
	private int jsViewIds[] = { R.id.js_value_1, R.id.js_value_2,
			R.id.js_value_3, R.id.js_value_4, R.id.js_value_5, R.id.js_value_6 };

	private void showBchaoPopWindow(View v, AddToldData addToldData) {
		View view = getLayoutInflater().inflate(R.layout.told_detail_pop_bchao,
				null);
		TextView leftOvaryTextArray[] = new TextView[8];
		TextView rightOvaryTextArray[] = new TextView[8];
		String[] leftOvaryValues = addToldData.getLeftovary().split(";");
		String[] rightOvaryValues = addToldData.getRightovary().split(";");

		for (int i = 0; i < 8; i++) {
			leftOvaryTextArray[i] = (TextView) view
					.findViewById(leftruanViewIds[i]);
			rightOvaryTextArray[i] = (TextView) view
					.findViewById(rightruanViewIds[i]);
			if (i < leftOvaryValues.length) {
				leftOvaryTextArray[i].setText(leftOvaryValues[i]);
			}
			if (i < rightOvaryValues.length) {
				rightOvaryTextArray[i].setText(rightOvaryValues[i]);
			}
		}
		if (addToldData.getAttach() != null) {
			addPopImage(view, addToldData);
		}
		if(!TextUtils.isEmpty(addToldData.getFeedback())){
			TextView bchao_feedback = (TextView)view.findViewById(R.id.bchao_feedback);
			bchao_feedback.setText(addToldData.getFeedback());
		}
		
		final PopupWindow popupWindow = new PopupWindow(this);
		popupWindow.setContentView(view);
		popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
		popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		// popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	private void showYanxuePopWindow(View v, AddToldData addToldData) {
		View view = getLayoutInflater().inflate(
				R.layout.told_detail_pop_yanxue, null);
		TextView jsViewArray[] = new TextView[6];
		String jsValues[] = addToldData.getBlood().split(";");
		for (int i = 0; i < 6; i++) {
			jsViewArray[i] = (TextView) view.findViewById(jsViewIds[i]);
			if (i < jsValues.length) {
				jsViewArray[i].setText(jsValues[i]);
			}
		}
		if (addToldData.getAttach() != null) {
			addPopImage(view, addToldData);
		}
		if(!TextUtils.isEmpty(addToldData.getFeedback())){
			TextView yanxue_feekback = (TextView)view.findViewById(R.id.yanxue_feekback);
			yanxue_feekback.setText(addToldData.getFeedback());
		}
		
		final PopupWindow popupWindow = new PopupWindow(this);
		popupWindow.setContentView(view);
		popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
		popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		// popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	private void addPopImage(View view, AddToldData addToldData) {
		LinearLayout wait_bchao_image_l = (LinearLayout) view
				.findViewById(R.id.wait_bchao_image_l);
		String imagesurl[] = addToldData.getAttach();
		wait_bchao_image_l.removeAllViews();
		for (int i = 0; i < imagesurl.length; i++) {
			final String url = imagesurl[i];
			ImageView imageView = new ImageView(this);
			imageView.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
			imageView.setScaleType(ScaleType.FIT_CENTER);
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startLookUpImage(url);
				}
			});

			ImageLoader.getInstance().loadNetWorkImage(
					AppUtil.getCompletePhotoUrl(url), imageView);
			wait_bchao_image_l.addView(imageView);
		}
	}

	private void startLookUpImage(String url) {
		try {
			Intent intent = new Intent("com.intent.action.lookup.image");
			intent.putExtra(LookupImageActivity.LOOKUP_IMAGE_PATH_KEY,
					AppUtil.getCompletePhotoUrl(url));
			intent.putExtra(LookupImageActivity.LOOKUP_IMAGE_TYPE,
					LookupImageActivity.NETWORK_IMAGE);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startModifyToldActivity(AddToldData item) {
		Intent intent = new Intent("com.intent.action.told.detail");
		intent.putExtra(ToldDetailActivity.TOLD_INTENT_DATA_KEY, item);
		intent.putExtra(ToldDetailActivity.TOLD_MODIFY_KEY, true);
		startActivityForResult(intent, TOLD_COMMIT_REQUEST_CODE);
	}

	@Override
	public void onToldDetailonClick(AddToldData item) {
		Intent intent = new Intent("com.intent.action.told.detail");
		intent.putExtra(ToldDetailActivity.TOLD_INTENT_DATA_KEY, item);
		startActivityForResult(intent, TOLD_COMMIT_REQUEST_CODE);
	}

	private void showRequireItemDialog(final int position) {
		if(docRequireData.get(position).getF_finished() == 1){
			return;
		}
		AlertDialog.Builder builder = new Builder(MyPeriodActivity.this);
		builder.setMessage(R.string.remove_told_dialog_msg);
		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {

					}
				});
		builder.setPositiveButton(R.string.told_remove_title,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						long id = docRequireData.get(position).getId();
						removeTold(id);
					}
				});
				builder.setNeutralButton(R.string.told_modify_title,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								AddToldData item = docRequireData.get(position);
								startModifyToldActivity(item);
							}
						});
		builder.create().show();
	}
}
